<?php

namespace App\CustHub\Helpers;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Contract\ConfigInterface;
use Psr\Container\ContainerInterface;

class ImageHelp
{
    private ClientFactory $clientFactory;
    private ConfigInterface $config;

    public function __construct(
        ContainerInterface $container,
        ClientFactory $clientFactory,
        ConfigInterface $config
    ) {
        $this->clientFactory = $clientFactory;
        $this->config = $config;
    }

    /**
     * 在图片中心添加 logo
     *
     * @param string $imageUrl 原图 URL
     * @param string $logoUrl logo URL
     * @param string $outputPath 输出路径
     * @param int $logoWidth logo 宽度（可选，自动调整）
     * @param int $logoHeight logo 高度（可选，自动调整）
     * @return bool
     */
    public function addLogoToImage(
        string $imageUrl,
        string $logoUrl,
        string $outputPath,
        int $logoWidth = 0,
        int $logoHeight = 0
    ): bool {
        try {
            // 下载原图
            $imageContent = $this->downloadImage($imageUrl);
            if (!$imageContent) {
                throw new \Exception('下载原图失败');
            }

            // 下载 logo
            $logoContent = $this->downloadImage($logoUrl);
            if (!$logoContent) {
                throw new \Exception('下载 logo 失败');
            }

            // 创建原图资源
            $image = imagecreatefromstring($imageContent);
            if (!$image) {
                throw new \Exception('创建原图资源失败');
            }

            // 创建 logo 资源
            $logo = imagecreatefromstring($logoContent);
            if (!$logo) {
                throw new \Exception('创建 logo 资源失败');
            }

            // 获取图片尺寸
            $imageWidth = imagesx($image);
            $imageHeight = imagesy($image);
            $logoOrigWidth = imagesx($logo);
            $logoOrigHeight = imagesy($logo);

            // 计算 logo 尺寸
            if ($logoWidth <= 0 || $logoHeight <= 0) {
                // 自动调整大小，默认为原图的 1/4
                $logoWidth = (int)($imageWidth / 4);
                $logoHeight = (int)($logoOrigHeight * ($logoWidth / $logoOrigWidth));
            }

            // 调整 logo 大小
            $resizedLogo = imagecreatetruecolor($logoWidth, $logoHeight);
            imagealphablending($resizedLogo, false);
            imagesavealpha($resizedLogo, true);

            imagecopyresampled(
                $resizedLogo,
                $logo,
                0, 0, 0, 0,
                $logoWidth,
                $logoHeight,
                $logoOrigWidth,
                $logoOrigHeight
            );

            // 计算 logo 位置（居中）
            $positionX = (int)(($imageWidth - $logoWidth) / 2);
            $positionY = (int)(($imageHeight - $logoHeight) / 2);

            // 合并图片
            imagecopy(
                $image,
                $resizedLogo,
                $positionX,
                $positionY,
                0,
                0,
                $logoWidth,
                $logoHeight
            );

            // 保存图片
            $result = imagejpeg($image, $outputPath, 90);

            // 释放内存
            imagedestroy($image);
            imagedestroy($logo);
            imagedestroy($resizedLogo);

            return $result;

        } catch (\Exception $e) {
            // 记录错误日志
            logger()->info('图片处理失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 下载图片
     *
     * @param string $url
     * @return string|null
     */
    private function downloadImage(string $url): ?string
    {
        try {
            $client = $this->clientFactory->create();
            $response = $client->get($url);

            if ($response->getStatusCode() === 200) {
                return $response->getBody()->getContents();
            }
        } catch (\Exception $e) {
            \Hyperf\Logger\LoggerFactory::get('log')->error('下载图片失败: ' . $e->getMessage());
        }

        return null;
    }

    /**
     * 支持 PNG 透明背景的版本
     *
     * @param string $imageUrl
     * @param string $logoUrl
     * @param string $outputPath
     * @param int $logoWidth
     * @param int $logoHeight
     * @return bool
     */
    public function addLogoWithTransparency(
        string $imageUrl,
        string $logoUrl,
        string $outputPath,
        int $logoWidth = 0,
        int $logoHeight = 0
    ): bool {
        try {
            $imageContent = $this->downloadImage($imageUrl);
            $logoContent = $this->downloadImage($logoUrl);

            if (!$imageContent || !$logoContent) {
                return false;
            }

            $image = imagecreatefromstring($imageContent);
            $logo = imagecreatefromstring($logoContent);

            if (!$image || !$logo) {
                return false;
            }

            $imageWidth = imagesx($image);
            $imageHeight = imagesy($image);
            $logoOrigWidth = imagesx($logo);
            $logoOrigHeight = imagesy($logo);

            if ($logoWidth <= 0 || $logoHeight <= 0) {
                $logoWidth = (int)($imageWidth / 4);
                $logoHeight = (int)($logoOrigHeight * ($logoWidth / $logoOrigWidth));
            }

            // 创建透明背景的 logo
            $resizedLogo = imagecreatetruecolor($logoWidth, $logoHeight);
            imagealphablending($resizedLogo, false);
            imagesavealpha($resizedLogo, true);
            $transparent = imagecolorallocatealpha($resizedLogo, 0, 0, 0, 127);
            imagefill($resizedLogo, 0, 0, $transparent);

            imagecopyresampled(
                $resizedLogo,
                $logo,
                0, 0, 0, 0,
                $logoWidth,
                $logoHeight,
                $logoOrigWidth,
                $logoOrigHeight
            );

            $positionX = (int)(($imageWidth - $logoWidth) / 2);
            $positionY = (int)(($imageHeight - $logoHeight) / 2);

            // 使用 imagecopymerge 支持透明度
            imagecopymerge(
                $image,
                $resizedLogo,
                $positionX,
                $positionY,
                0,
                0,
                $logoWidth,
                $logoHeight,
                100
            );

            $result = imagepng($image, $outputPath, 9);

            imagedestroy($image);
            imagedestroy($logo);
            imagedestroy($resizedLogo);

            return $result;

        } catch (\Exception $e) {
            \Hyperf\Logger\LoggerFactory::get('log')->error('图片处理失败: ' . $e->getMessage());
            return false;
        }
    }
}